package io.renren.modules.generator.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.Constant;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisKeys;
import io.renren.common.utils.RedisService;
import io.renren.modules.generator.dao.AddressCustomerDao;
import io.renren.modules.generator.dao.CustomerDao;
import io.renren.modules.generator.entity.AddressCustomerEntity;
import io.renren.modules.generator.entity.CustomerEntity;
import io.renren.modules.generator.entity.ProjectEntity;
import io.renren.modules.generator.service.CustomerService;
import io.renren.modules.generator.service.ProjectService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("customerService")
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, CustomerEntity> implements CustomerService {

    @Autowired
    private  CustomerDao customerDao;

    @Autowired
    private AddressCustomerDao addressCustomerDao;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ProjectService projectService;


    @Override
    public List<CustomerEntity> queryPage(Map<String, Object> params) {

        return customerDao.queryPage(params);
    }
    @Override
    public  int queryPageTotal(Map<String, Object> params) {

        return customerDao.queryPageTotal(params);
    }

    @Override
    @Transactional
    public void update(CustomerEntity customer) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("customer_id",customer.getId());
        addressCustomerDao.deleteByMap(map);
        insertAddressCustomer(customer.getCustomerAddressIds(),customer.getId());
        this.updateById(customer);
        redisService.remove(RedisKeys.getCustomerKey(customer.getCode()));
    }

    @Override
    @Transactional
    public void save(CustomerEntity customer) {
        this.insert(customer);
        insertAddressCustomer(customer.getCustomerAddressIds(),customer.getId());
    }

    @Override
    public void updateStatusByIds(List<Integer> list) {
        customerDao.updateStatusByIds(list);
    }

    @Override
    public CustomerEntity info(Integer id) {
        return customerDao.queryById(id);
    }

    @Override
    public CustomerEntity queryEntityByCode(String code) {
        return this.selectOne(new EntityWrapper<CustomerEntity>().eq(StringUtils.isNotBlank(code),"code",code));
    }

    @Override
    @Transactional
    public R importFile(Workbook book) {
        List<CustomerEntity> customerEntities = new ArrayList<>();

        Sheet sheet = book.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            CustomerEntity customerEntity = new CustomerEntity();

            if(row.getCell(0) != null && !row.getCell(0).toString().trim().equals("")){
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                String customerCode =  row.getCell(0).getStringCellValue().trim();
                if(customerCode.equals("end")){
                    break;
                }

                customerEntity.setCode(customerCode);

            }else{
                return R.error("第"+i+"行客户代码不能为空");
            }

            /**
             * 客户名称
             */
            if(row.getCell(1) != null && !row.getCell(1).toString().trim().equals("")){
                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                String customerCnName =  row.getCell(1).getStringCellValue().trim();
                customerEntity.setCnName(customerCnName);

            }else{
                return R.error("第"+i+"行客户名称不能为空");
            }

            /**
             * 客户英文名称
             */
            if(row.getCell(2) != null && !row.getCell(2).toString().trim().equals("")){
                row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                String enName =  row.getCell(2).getStringCellValue().trim();
                customerEntity.setEnName(enName);

            }
            /**
             * 客户属性
             */
            if(row.getCell(4) != null && !row.getCell(4).toString().trim().equals("")){
                row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                String propertyId =  row.getCell(4).getStringCellValue().trim();
                customerEntity.setCustomerPropertyDictionaryId(Integer.valueOf(propertyId));

            }

            /**
             * 结算属性
             */
            if(row.getCell(6) != null && !row.getCell(6).toString().trim().equals("")){
                row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                String settlementPropertyDictionaryId =  row.getCell(6).getStringCellValue().trim();
                customerEntity.setSettlementPropertyDictionaryId(Integer.valueOf(settlementPropertyDictionaryId));

            }

            /**
             * 所属项目
             */

            if(row.getCell(7) != null && !row.getCell(7).toString().trim().equals("")){
                row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
                String projectCode =  row.getCell(7).getStringCellValue().trim();
                String projectKey = RedisKeys.getProjectKey(projectCode);
                Object o = redisService.get(projectKey);
                ProjectEntity projectEntity = null;
                if(o != null){
                    projectEntity = (ProjectEntity) o;
                }else{
                    projectEntity = projectService.queryEntityByCode(projectCode);
                    if(projectEntity != null){
                        redisService.set(projectKey,projectEntity, Constant.getRedisKeyExpireTimeDayToSecond(7));
                    }else{
                        return R.error("第"+i+"行项目代码["+projectCode+"]没有维护，请先维护");
                    }
                }
               customerEntity.setProjectId(projectEntity.getId());
            }else{
                return R.error("第"+i+"行项目代码不能为空");
            }



            /**
             * 备注
             */
            if(row.getCell(9) != null && !row.getCell(9).toString().trim().equals("")){
                row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
                String remark =  row.getCell(9).getStringCellValue().trim();
                customerEntity.setRemark(remark);
            }

            /**
             * 预留字段1
             */
            if(row.getCell(10) != null && !row.getCell(10).toString().trim().equals("")){
                row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
                String extendFirst =  row.getCell(10).getStringCellValue().trim();
                customerEntity.setExtendFirst(extendFirst);
            }
            /**
             * 预留字段2
             */
            if(row.getCell(11) != null && !row.getCell(11).toString().trim().equals("")){
                row.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
                String extendSecond =  row.getCell(11).getStringCellValue().trim();
                customerEntity.setExtendSecond(extendSecond);
            }

            /**
             * 预留字段3
             */
            if(row.getCell(12) != null && !row.getCell(12).toString().trim().equals("")){
                row.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
                String extendThird =  row.getCell(12).getStringCellValue().trim();
                customerEntity.setExtendThird(extendThird);
            }


            customerEntities.add(customerEntity);



        }

        String code="";

        try{
            if(customerEntities.size()>0){
                for (CustomerEntity customer :
                        customerEntities) {
                    code = customer.getCode();
                    this.insert(customer);
                }
            }
        }catch (DuplicateKeyException d){
            d.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new DuplicateKeyException("客户代码[ "+code+" ]已经存在,请不要重复导入");
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

        }
        return R.ok();
    }

    @Override
    public List<CustomerEntity> queryEntitiesList(String code) {
        List<CustomerEntity> customerEntities = this.selectList(new EntityWrapper<CustomerEntity>()
                .like(StringUtils.isNotBlank(code), "code", code));
        return customerEntities;
    }

    @Override
    public List<CustomerEntity> queryEntitiesListByAddressId(Integer addressId) {
        return customerDao.queryEntitiesListByAddressId(addressId);
    }


    private void insertAddressCustomer( List<Integer> addressIds, int customerId){
        for (int id: addressIds){
            AddressCustomerEntity addressCustomerEntity = new AddressCustomerEntity();
            addressCustomerEntity.setAddressId(id);
            addressCustomerEntity.setCustomerId(customerId);

            addressCustomerDao.insert(addressCustomerEntity);
        }
    }



}
